<?php

namespace App\Http\Controllers;

use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{
  public function __construct(Request $request)
  {
    parent::__construct($request, 'User', 'UserResource');
  }

  public function store(Request $request)
  {
    Log::debug(__METHOD__);

    $newuser = $newresource = $validator = $response = null;
    $values = [];

    $values = $request->all();
    $role = Role::where('slug', config('coreapi.created_user_role'))->first();
    $values['role_id'] = $role->id;
    $validator = Validator::make($values, $this->model::$insertRules);
    if ($validator->fails()) {
      $response = response()->json(['error' => $validator->errors()], 400);
    } else {
      $newuser = $this->model::create($values);
      $newuser->update(['active' => true]);
      $newuser = $this->model::find($newuser->id);
      $newresource = new $this->resource($newuser);
      $response = response()->json([
        'resource' => $newresource,
        'message' => trans('coreapi.resource_created'),
      ], 201);
    }

    return $response;
  }
}
